﻿using MQTTnet.Client.Options;
using MQTTnet.Client.Subscribing;
using MQTTnet.Client.Unsubscribing;
using MQTTnet.Client;
using MQTTnet;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Extensions.Hosting;
using Modules.Cms;
using PmSoft;
using Microsoft.Extensions.DependencyInjection;

namespace MQTTServer.Services
{
    public class MQTTClient
    {


        private IMqttClient mqttClient;
        public MQTTClient()
        {

        }
        public void StartClient()
        {

            ConnectToServer();
            Thread.Sleep(500);
            ClientSubscribeTopic("/think_php/init_truck");
        }


        private void ConnectToServer()
        {
            try
            {
                // 1. 创建 MQTT 客户端
                mqttClient = new MqttFactory().CreateMqttClient();


                // 2 . 设置 MQTT 客户端选项
                MqttClientOptionsBuilder optionsBuilder = new MqttClientOptionsBuilder();

                // 设置服务器端地址
                optionsBuilder.WithTcpServer("192.168.25.31", 1884);

                // 设置鉴权参数
                optionsBuilder.WithCredentials("admin", "eHIGH2014");

                // 设置客户端序列号
                optionsBuilder.WithClientId(Guid.NewGuid().ToString());

                // 创建选项
                IMqttClientOptions options = optionsBuilder.Build();


                // 设置消息接收处理程序
                mqttClient.UseApplicationMessageReceivedHandler(args =>
                {
                    Console.WriteLine("### 收到来自服务器端的消息 ###");
                    // 收到的消息主题
                    string topic = args.ApplicationMessage.Topic;
                    // 收到的的消息内容
                    string payload = Encoding.UTF8.GetString(args.ApplicationMessage.Payload);
                    // 收到的发送级别(Qos)
                    var qos = args.ApplicationMessage.QualityOfServiceLevel;
                    // 收到的消息保持形式
                    bool retain = args.ApplicationMessage.Retain;

                    Console.WriteLine($"主题: [{topic}] 内容: [{payload}] Qos: [{qos}] Retain:[{retain}]");
                });

                // 重连机制
                mqttClient.UseDisconnectedHandler(async e =>
                {
                    Console.WriteLine("与服务器之间的连接断开了，正在尝试重新连接");
                    // 等待 5s 时间
                    await Task.Delay(TimeSpan.FromSeconds(5));
                    try
                    {
                        // 重新连接
                        await mqttClient.ConnectAsync(options);
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine($"重新连接服务器失败:{ex}");
                    }
                });

                // 连接到服务器
                mqttClient.ConnectAsync(options);
                Console.WriteLine("连接服务器成功！请输入任意内容并回车进入菜单界面");


            }
            catch (Exception ex)
            {
                Console.Write($"连接服务器失败: {ex}");
            }
        }



        private async void ClientSubscribeTopic(string topic)
        {
            topic = topic.Trim();
            if (string.IsNullOrEmpty(topic))
            {
                Console.Write("订阅主题不能为空！");
                return;
            }

            // 判断客户端是否连接
            if (!mqttClient.IsConnected)
            {
                Console.WriteLine("MQTT 客户端尚未连接!");
                return;
            }

            // 设置订阅参数
            var subscribeOptions = new MqttClientSubscribeOptionsBuilder()
                .WithTopicFilter(topic)
                .Build();

            // 订阅
            await mqttClient.SubscribeAsync(
                    subscribeOptions,
                    System.Threading.CancellationToken.None);
        }
    }
}
